<?php

/**
 * ArticleService.class.php 文章服务层
 * Created Time 2016年3月25日 下午6:37:05
 *
 * @author     codingyuan@163.com
 */
namespace Home\Service;

use Home\Common\Service;

class ArticleService extends Service {

    protected $articleMdl;
    protected $extendMdl;
    public function __construct()
    {
        parent::__construct();
        $this->articleMdl = D('Home/Article');
        $this->extendMdl = D('Home/ArticleField');
    }
    
    /**
     * 获取文章编辑数据
     * @param int $id
     * @return array
     * */
    public function getEditRow($id)
    {
        // 查看文章是否存在
        $this->hasMasterOne($id);
        // 获取数据
        $master = array();
        $extend = array();
        // 获取主表数据
        $master = $this->articleMdl
                  ->where('aid=%d', intval($id))
                  ->field('title,cid,source,sourl,face_atid,is_publish,is_comment')
                  ->find();
        // 获取扩展表数据
        $extend = $this->extendMdl
                  ->where('aid=%d', intval($id))
                  ->field('description,tags,content')
                  ->find();
        $editData = array_merge($master, $extend);
        
        return $editData;
    }
    
    // 查看文章是否存在
    public function hasMasterOne($id)
    {
        if(!$id || !is_numeric($id))
        {
            throw new \Exception(L('_ERR_FORMART_AID_'));
        }
        
        $rs = $this->articleMdl->where('aid=%d',intval($id))->field('aid')->find();
        if(!$rs)
        {
            throw new \Exception(L('_ERR_NOT_HAS_'));
        }
        
        return true;
    }
    
    /**
     *  保存文章数据
     *  @param array $data
     *  @param int &$id
     *  @return bool
     * */
    public function saveData($data, &$aid)
    {
        // 验证数据
        $this->__checkData($data);
        
        // 组合入库数据
        $combinData = array();
        $this->__combinData($data, $combinData);
        try {
            // 开启事务
            $this->articleMdl->startTrans();
            // 如果文章主键存在就是更新，不存在就是添加
            if(isset($combinData['aid']) && is_numeric($combinData['aid']))
            {
                $aid = $combinData['aid'];
                // 更新主表
                $combinData['master']['updated'] = NOW_TIME;
                $this->articleMdl->where('aid=%d', intval($aid))->save($combinData['master']);
                // 更新扩展表
                $combinData['extend']['updated'] = NOW_TIME;
                $this->extendMdl->where('aid=%d', intval($aid))->save($combinData['extend']);
            }
            else
            {
                // 添加主表
                $combinData['master']['created'] = $combinData['master']['updated'] = NOW_TIME;
                $aid = $this->articleMdl->add($combinData['master']);
                if(!$aid)
                {
                    throw new \Exception(L('_ERR_SAVE_'));
                }
                
                // 添加扩展表
                $combinData['extend']['created'] = $combinData['extend']['updated'] = NOW_TIME;
                $combinData['extend']['aid'] = $aid;
                $rs = $this->extendMdl->add($combinData['extend']);
                if(!$rs)
                {
                    throw new \Exception(L('_ERR_SAVE_'));
                }
            }
            
            $this->articleMdl->commit();
        } catch (\Exception $e) {
            $this->articleMdl->rollback();
            throw $e;
            
            return false;
        }
        
        return true;
    }
    
    private function __combinData($data, &$result)
    {
        // 过滤数据
        $tmpData = \Component\Tools\Specialutils::filterInput($data);
        $tmpData['tags'] = strip_tags($data['tags']);
        $data = $tmpData;
        
        // 主表数据
        $master = array();
        // 扩展表数据
        $extend = array();
        
        // 开始整理
        if(isset($data['article-actid']) && $data['article-actid'])
        {
            $master['cid'] = (int)$data['article-actid'];
        }
        
        if(isset($data['article-title']) && $data['article-title'])
        {
            $master['title'] = $data['article-title'];
        }
        
        if(isset($data['source']) && $data['source'])
        {
            $master['source'] = $data['source'];
        }
        
        if(isset($data['sourl']) && $data['sourl'])
        {
            $master['sourl'] = $data['sourl'];
        }
        
        if(isset($data['article-desc']) && $data['article-desc'])
        {
            $extend['description'] = $data['article-desc'];
        }
        
        if(isset($data['attids']) && $data['attids'])
        {
            $master['face_atid'] = (int)$data['attids'];
        }
        
        if(isset($data['tags']) && $data['tags'])
        {
            $extend['tags'] = $data['tags'];
        }
        
        if(isset($data['is_publish']) && $data['is_publish'])
        {
            $master['is_publish'] = (int)$data['is_publish'];
        }
        
        if(isset($data['is_comment']) && $data['is_comment'])
        {
            $master['is_comment'] = (int)$data['is_comment'];
        }
        
        if(isset($data['content']) && $data['content'])
        {
            $extend['content'] = $data['content'];
        }
        
        if(isset($data['id']) && $data['id'])
        {
            $result['aid'] = (int)$data['id'];
        }
        
        $result['master'] = $master;
        $result['extend'] = $extend;
        
        return true;
    }
    
    private function __checkData($data)
    {
        $errors = array();
        $options = array(
                'article-title' =>array(
                        'required' => array(
                            'rule'=>true,
                            'message'=>L('_ERR_EMPTY_TITLE_')
                        ),
                        'string_count_in_range' => array(
                                'rule'=>array(2,100),
                                'message'=>L('_ERR_LENGTH_TITLE_', array('min'=>2, 'max'=>100))
                        ),
                ),
                'article-actid' =>array(
                        'required' => array(
                                'rule'=>true,
                                'message'=>L('_ERR_EMPTY_CAT_')
                        ),
                ),
                'content' =>array(
                        'required' => array(
                                'rule'=>true,
                                'message'=>L('_ERR_EMPTY_CONTENT_')
                        ),
                ),
        );
        
        $rs = \Component\Tools\Validator::make($errors, $data, $options);
        if(!$rs)
        {
            foreach ($errors as $k=>$v)
            {
                throw new \Exception($v);
            }
        }
        
        // 判断url是否合法
        if($data['sourl'])
        {
            if(! $rs = \Component\Tools\Validator::is_url($data['sourl']))
            {
                throw new \Exception(L('_ERR_FORMART_URL_'));
            }
            
        }
        
        return $rs;
    }
    
    
}

